/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import AccesoADatos.ServicioPermisoTableSpace;
import Logica.Clasificacion;
import Logica.Columna;
import Logica.Tabla;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author David
 */
public class Catalogo extends javax.swing.JPanel {

    
    public ArrayList<Clasificacion> clasificaciones;
    ConectadoGUI conectado;
    Catalogo catalogo;
    Clasificacion classSelecionada;
    private ServicioPermisoTableSpace serTS;
    
    public Catalogo(ConectadoGUI c) {
        initComponents();
        this.conectado = c;
        clasificaciones = new ArrayList();
        
        cargarArchivo();
        cargarTabla();
        catalogo = this;
    }
        
    public void cargarTabla(){
        
        //borra toda la tabla primero
        for(int i=0;i<((DefaultTableModel)getClassTabla().getModel()).getRowCount();){
            ((DefaultTableModel)getClassTabla().getModel()).removeRow(i);
        }
        
        //agrega lo que haya en el arraylist
        for(int i=0;i<clasificaciones.size();i++){
            Clasificacion c = clasificaciones.get(i);
            ((DefaultTableModel)getClassTabla().getModel()).addRow(new Object[]{c.getClasificacion(),c.getDescripcion()});
        }        
    }
    

    public void cargarArchivo(){
        Clasificacion c = null;
        try
        {
           FileInputStream fileIn = new FileInputStream("catalog.txt");
           ObjectInputStream in = new ObjectInputStream(fileIn);
           ArrayList<Clasificacion> cla;
           cla = (ArrayList<Clasificacion>) in.readObject();
           if(cla!=null){
               clasificaciones = cla;
           }
           in.close();
           fileIn.close();
        }catch(IOException i)
        {
           i.printStackTrace();
           return;
        }catch(ClassNotFoundException e)
        {
           System.out.println("Clasificacion class not found");
           e.printStackTrace();
           return;
        }
    }
    
    public void guardarArchivo(){
        try {
            FileOutputStream fileOut =
                    new FileOutputStream("catalog.txt");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            out.writeObject(clasificaciones);
           
            out.close();
            fileOut.close();
            System.out.printf("Serialized data is saved in catalog.txt");
        } catch (IOException i) {
            i.printStackTrace();
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        newBoton = new javax.swing.JButton();
        deleteBoton = new javax.swing.JButton();
        changeBoton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        classTabla = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Categories"));

        newBoton.setText("New");
        newBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newBotonActionPerformed(evt);
            }
        });

        deleteBoton.setText("Delete");
        deleteBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBotonActionPerformed(evt);
            }
        });

        changeBoton.setText("Change");
        changeBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeBotonActionPerformed(evt);
            }
        });

        classTabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Categories", "Description"
            }
        ));
        classTabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                classTablaMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(classTabla);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(newBoton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteBoton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(changeBoton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newBoton)
                    .addComponent(deleteBoton)
                    .addComponent(changeBoton))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Privileges"));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Table_Name", "Column_Name", "Insert", "Delete", "Alter", "Select", "Update"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void newBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newBotonActionPerformed
        EditarClasificacion ec = new EditarClasificacion(this,conectado.getConexion().user,conectado.getConexion().pass,conectado.getConexion().ip,conectado.getConexion().port,conectado.getConexion().db);
        ec.setVisible(true);
    }//GEN-LAST:event_newBotonActionPerformed

    private void classTablaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classTablaMouseReleased
        getClassTabla().getSelectionModel().setSelectionInterval(getClassTabla().rowAtPoint(evt.getPoint()), getClassTabla().rowAtPoint(evt.getPoint()));
        final String clasificacion;            
        clasificacion=(String) getClassTabla().getModel().getValueAt(getClassTabla().rowAtPoint(evt.getPoint()),0);
        System.out.println(clasificacion);
        
        if(SwingUtilities.isRightMouseButton(evt)){
            //System.out.println(this.classTabla.rowAtPoint(evt.getPoint()));       
                  
            
            for(int i=0;i<clasificaciones.size();i++){
                if(clasificaciones.get(i).getClasificacion().equals(clasificacion)){
                    classSelecionada = clasificaciones.get(i);
                    break;
                }
            }
            
            final JPopupMenu menu = new JPopupMenu();
            JMenuItem dp = new JMenuItem("Configuration");
            
            
            dp.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                JFrame frame=new JFrame();
                                frame.setTitle("Privilege Configuration ("+clasificacion+")");
                                frame.setResizable(false);
                                PermisosTableSpace panel=new PermisosTableSpace(classSelecionada,frame,conectado,catalogo);
                                panel.setConection(conectado.getConexion().user, conectado.getConexion().pass,conectado.getConexion().ip,conectado.getConexion().port,conectado.getConexion().db);
                                frame.setContentPane(panel);
                                frame.pack();
                                frame.validate();
                                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                                frame.setVisible(true);
                            }
                        });
            
            
            menu.add(dp);
            menu.show(evt.getComponent(),evt.getX(),evt.getY());
        }else{
            Clasificacion aux=getClasificacion(clasificacion);
            Tabla auxTabla;
            Columna auxCol;
            clearTable(jTable1);
            //System.out.println(aux.getClasificacion()+aux.getDescripcion()+aux.getNombreRol());
            for(int i=0;i<aux.getTablaPermisos().size();i++){
                auxTabla=aux.getTablaPermisos().get(i);
                ((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{auxTabla.getNombre(),"",auxTabla.isInsert(),auxTabla.isDelete(),auxTabla.isAlter(),auxTabla.isSelect(),false});
                for(int x=0;x<auxTabla.getColumans().size();x++){
                    auxCol=auxTabla.getColumans().get(x);
                    //Columnas
                    ((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{auxTabla.getNombre(),auxCol.getNombre(),auxCol.isInsert(),false,false,false,auxCol.isUpdate()});
                }
            }
        }
    }//GEN-LAST:event_classTablaMouseReleased
    
    
    public void clearTable(JTable tabla){
        while(tabla.getModel().getRowCount()>0){
            ((DefaultTableModel)tabla.getModel()).removeRow(0);
        }
    }
    
    public Clasificacion getClasificacion(String clasificacion){
        for(int i=0;i<clasificaciones.size();i++){
            if(clasificaciones.get(i).getClasificacion().equals(clasificacion)){
                return clasificaciones.get(i);
            }
        }
        return null;
    }
    
    private void deleteBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBotonActionPerformed
        // TODO add your handling code here:
        int index = getClassTabla().getSelectedRow();
        if(index==-1){
            JOptionPane.showMessageDialog(this, "Select a row", "warning", 1);
        }else{
           serTS=new ServicioPermisoTableSpace(conectado.getConexion().user,conectado.getConexion().pass,conectado.getConexion().ip,conectado.getConexion().port,conectado.getConexion().db);

            try {
                String role=(String) getClassTabla().getModel().getValueAt(index, 0);
                //System.out.println(role);
                serTS.dropRole(role);
            } catch (    SQLException | ClassNotFoundException ex) {
                Logger.getLogger(Catalogo.class.getName()).log(Level.SEVERE, null, ex);
            }            
            
            ((DefaultTableModel)getClassTabla().getModel()).removeRow(index);        
            clearTable(jTable1);
            clasificaciones.remove(index);
            
            guardarArchivo();
        }
        
        
    }//GEN-LAST:event_deleteBotonActionPerformed

    private void changeBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeBotonActionPerformed
        int index = getClassTabla().getSelectedRow();
        if(index==-1){
            JOptionPane.showMessageDialog(this, "Select a row", "warning", 1);
        }else{
            EditarClasificacion ec = new EditarClasificacion(this,index);
            ec.setVisible(true);
        }
    }//GEN-LAST:event_changeBotonActionPerformed

    public javax.swing.JTable getClassTabla() {
        return classTabla;
    }

    public void setClassTabla(javax.swing.JTable classTabla) {
        this.classTabla = classTabla;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton changeBoton;
    private javax.swing.JTable classTabla;
    private javax.swing.JButton deleteBoton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton newBoton;
    // End of variables declaration//GEN-END:variables
}
